import { createRouter, createWebHashHistory } from 'vue-router'



// 2 路由独享守卫
function hasUrl(to,next){
  let menus_url = JSON.parse(localStorage.getItem('userinfo') || '{}' ).menus_url
  let pathUrl = to.path.split('/')  // /index/menu
  let path = '/' + pathUrl[pathUrl.length-1]  // /menu
  if( menus_url.includes(path) ){  // true
    next()
  }else{
    // 没有权限
    next('/login')
  }
}

const routes = [
  // 一级路由
  {
    path: '/login',
    component: () => import('@/pages/login'),
    meta: {
      title: '登陆'
    }
  },
  {
    path: '/index',
    component: () => import('@/pages/index'),
    meta: {
      title: '首页'
    },
    // 二级路由
    children: [
      {
        path: 'home',
        component: () => import('@/views/index'),
        meta: {
          title: '首页'
        }
      },
      {
        path: 'menu',
        component: () => import('@/views/menu/menu'),
        meta: {
          title: '菜单管理'
        },
        beforeEach(to,from,next){ hasUrl(to,next) }
      },
      {
        path: 'role',
        component: () => import('@/views/role'),
        meta: {
          title: '角色管理'
        }
      },
      {
        path: 'user',
        component: () => import('@/views/user/user'),
        meta: {
          title: '管理员管理'
        }
      },
      {
        path: 'cate',
        component: () => import('@/views/cate/cate'),
        meta: {
          title: '商品分类'
        }
      },
      {
        path: 'specs',
        component: () => import('@/views/specs'),
        meta: {
          title: '商品规格'
        }
      },
      {
        path: 'goods',
        component: () => import('@/views/goods'),
        meta: {
          title: '商品管理'
        }
      },
      {
        path: 'member',
        component: () => import('@/views/member'),
        meta: {
          title: '会员管理'
        }
      },
      {
        path: 'banner',
        component: () => import('@/views/banner'),
        meta: {
          title: '轮播图管理'
        }
      },
      {
        path: 'seck',
        component: () => import('@/views/seck'),
        meta: {
          title: '秒杀活动'
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 1. 全局路由导航守卫
router.beforeEach((to,from,next)=>{
  if(to.path == '/login'){
    next()
    return
  }
  if( localStorage.getItem('userinfo') ){  // 有字符串， null
    next()
  }else{
    next('/login')
  }
})

export default router
